package com.ycb.filter;

import com.alibaba.fastjson.JSON;
import com.ycb.common.BaseContext;
import com.ycb.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;

/**
 * @Author ycb 过滤器
 * @Version 1.0
 * @Date 2024/10/4 11:16
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String requestURI = httpServletRequest.getRequestURI();
        log.info("拦截到请求:{}",requestURI);
        //定义不需要处理的请求路径
        String[] urls = new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
                // "/common/**"
        };

        //2.判断本地请求是否需要处理
        boolean check = check(urls, requestURI);

        //3.如果不需要处理，则直接放行
        if (check) {
            log.info("不需要处理的uri:{}",requestURI);
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //4.判断登陆状态，如果已经登录，则直接放行
        if (httpServletRequest.getSession().getAttribute("employee") != null) {
            long employeeId = (long)httpServletRequest.getSession().getAttribute("employee");
            log.info("用户已经登录，用户信息:{}",employeeId);
            BaseContext.setCurrentUserId(employeeId);
            long id = Thread.currentThread().getId();
            log.info("updateFill的线程id为：{}", id);
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        log.info("用户未登录");
        //5.如果未登录，则返回登录页面，通过输出流的方式相客户端返回数据
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
        // log.info("拦截到请求:{}",httpServletRequest.getRequestURL());
        // filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    /**
     * 判断地址是否属于不需要处理的地址
     * @param urls
     * @param requestUri
     * @return
     */
    public boolean check(String[] urls,String requestUri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
